package my.ezbart;

import java.util.ArrayList;
import java.util.Map;
import org.xmlvm.iphone.CGRect;
import org.xmlvm.iphone.CGSize;
import org.xmlvm.iphone.NSData;
import org.xmlvm.iphone.NSErrorHolder;
import org.xmlvm.iphone.NSHTTPURLResponseHolder;
import org.xmlvm.iphone.NSIndexPath;
import org.xmlvm.iphone.NSMutableURLRequest;
import org.xmlvm.iphone.NSURL;
import org.xmlvm.iphone.NSURLConnection;
import org.xmlvm.iphone.NSXMLParser;
import org.xmlvm.iphone.NSXMLParserDelegate;
import org.xmlvm.iphone.UIColor;
import org.xmlvm.iphone.UIImage;
import org.xmlvm.iphone.UILabel;
import org.xmlvm.iphone.UIScreen;
import org.xmlvm.iphone.UIScrollView;
import org.xmlvm.iphone.UITableView;
import org.xmlvm.iphone.UITableViewCell;
import org.xmlvm.iphone.UITableViewController;
import org.xmlvm.iphone.UITableViewDataSource;
import org.xmlvm.iphone.UITableViewDelegate;
import org.xmlvm.iphone.UITableViewStyle;
import org.xmlvm.iphone.UIView;
import org.xmlvm.iphone.UIViewController;

/**
 * @author Cecil Holmes
 * @version 0.1
 * 
 * RealTimeArrivals.java (3rd tab on the tab bar)
 * 
 * View Controller that retrieves real-time BART train arrival data. 
 * 
 * Holds a Table View similar to the Select Station View Controller and uses the selected station to retrieve
 * the corresponding real-time data from BART's Estimated Time of Arrival XML Feed.
 */ 
public class RealTimeArrivals extends UIViewController {
    private UIView root = new UIView(UIScreen.mainScreen().getApplicationFrame());
    private UIScrollView sv = new UIScrollView();
    private UIView newView = new UIView(new CGRect(0,0, UIScreen.mainScreen().getBounds().size.width, UIScreen.mainScreen().getBounds().size.height-110)); 
    private UITableViewController stationsController = new UITableViewController(UITableViewStyle.Plain);
    private UITableView stationsTable = stationsController.getTableView();
    private final static String[] stations = {
    		"12th St. Oakland City Center",
    	    "16th St. Mission",
    	    "19th St. Oakland",
    	    "24th St. Mission",
    	    "Ashby",
    	    "Balboa Park",
    	    "Bay Fair",
    	    "Castro Valley",
    	    "Civic Center/UN Plaza",
    	    "Coliseum/Oakland Airport",
    	    "Colma",
    	    "Concord",
    	    "Daly City",
    	    "Downtown Berkeley",
    	    "Dublin/Pleasanton",
    	    "El Cerrito del Norte",
    	    "El Cerrito Plaza",
    	    "Embarcadero",
    	    "Fremont",
    	    "Fruitvale",
    	    "Glen Park",
    	    "Hayward",
    	    "Lafayette",
    	    "Lake Merritt",
    	    "MacArthur",
    	    "Millbrae",
    	    "Montgomery St.",
    	    "North Berkeley",
    	    "North Concord/Martinez",
    	    "Orinda",
    	    "Pittsburg/Bay Point",
    	    "Pleasant Hill/Contra Costa Centre",
    	    "Powell St.",
    	    "Richmond",
    	    "Rockridge",
    	    "San Bruno",
    	    "San Francisco Int'l Airport",
    	    "San Leandro",
    	    "South Hayward",
    	    "South San Francisco",
    	    "Union City",
    	    "Walnut Creek",
    	    "West Dublin/Pleasanton",
    	    "West Oakland"};

    public RealTimeArrivals() {
        /*
         * The title is used by the UITabBarController as the caption for
         * the tab.
         */
    		this.setTitle("Real-Time Arrivals");
        
    	/*
         * The following statement associates an icon with the tab.
         * Ordinarily each tab would have an individual icon.
         */
        this.getTabBarItem().setImage(UIImage.imageNamed("11-clock.png"));
    }
    
    /**
     * Helper function to retrieve an item from a given (section, row).
     */
    private String getItem(int row) {
        return stations[row];
    }
    
    public class TableDataSource extends UITableViewDataSource {

        public String titleForHeaderInSection(UITableView table, int section) {
            return "Select Station";
        }
        
		@Override
		public UITableViewCell cellForRowAtIndexPath(UITableView view, NSIndexPath index) {
            UITableViewCell tc = new UITableViewCell();
            UILabel label = tc.getTextLabel();
            label.setAdjustsFontSizeToFitWidth(true);
            label.setText(stations[index.getRow()]);

            return tc;
		}

		@Override
		public int numberOfRowsInSection(UITableView view, int section) {
			return stations.length;
		}
    	
    }

    public class TableDelegate extends UITableViewDelegate {
    	
    	public void didSelectRowAtIndexPath(UITableView tableview, NSIndexPath index) {
            /**
             * This method will be called whenever the user selected a
             * particular row in the table. The specific row is given as the
             * usual (row).
             */
    		String origin = getItem(index.getRow());
    		final ArrayList<String> realTimeData = doXML(origin);
    		
    		UIViewController realTimeResults = new UIViewController() {
    			public void loadView() {
    				UIView root = new UIView(UIScreen.mainScreen().getApplicationFrame());
    				root.setBackgroundColor(UIColor.groupTableViewBackgroundColor);
    				
    				UIScrollView sv = new UIScrollView();
    				sv.setFrame(new CGRect(0, 0, UIScreen.mainScreen().getApplicationFrame().size.width, UIScreen.mainScreen().getBounds().size.height-110));
    		        sv.setContentSize(new CGSize(UIScreen.mainScreen().getApplicationFrame().size.width, UIScreen.mainScreen().getBounds().size.height-70));
    		        sv.setScrollEnabled(true);
    				
    				for(int i=0; i<realTimeData.size(); i++) {
    					UILabel label;
    					
    					if( (i > 2) && (i%2 == 1) ) {
    						label = new UILabel(new CGRect(10, ((i+2)*21), UIScreen.mainScreen().getApplicationFrame().size.width, 20));
        					label.setTextColor(UIColor.blackColor);
    					} else if(i > 2) {
    						label = new UILabel(new CGRect(10, ((i+2)*21), UIScreen.mainScreen().getApplicationFrame().size.width, 20));
    						label.setTextColor(UIColor.darkGrayColor);
    					} else {
    						label = new UILabel(new CGRect(10, ((i+1)*21), UIScreen.mainScreen().getApplicationFrame().size.width, 20));
        					label.setTextColor(UIColor.blackColor);
    					}
    					
    					label.setText(realTimeData.get(i));
    					label.setAdjustsFontSizeToFitWidth(true);
    					label.setBackgroundColor(UIColor.clearColor);
    					label.setShadowColor(UIColor.whiteColor);
    					label.setShadowOffset(new CGSize(0,1));
    					sv.addSubview(label);
    				}
    				
    				root.addSubview(sv);
    				this.setTitle("Arrivals");
    				this.setView(root);
    			}
    		};
    		
    		stationsTable.reloadData();
    		getNavigationController().pushViewController(realTimeResults, true);
        }
    }

    @Override
    public void loadView() {

        stationsTable.setDataSource(new TableDataSource());
        stationsTable.setDelegate(new TableDelegate());

        root.setBackgroundColor(UIColor.groupTableViewBackgroundColor);
        newView.setBackgroundColor(UIColor.groupTableViewBackgroundColor);
       
        sv.setFrame(new CGRect(0,0, UIScreen.mainScreen().getBounds().size.width, UIScreen.mainScreen().getBounds().size.height-111));
        sv.setBackgroundColor(UIColor.groupTableViewBackgroundColor);
        sv.setContentSize(newView.getBounds().size);
        sv.setScrollEnabled(true);
        
        stationsTable.setFrame(sv.getFrame());
        
        newView.addSubview(stationsTable);
        sv.addSubview(newView);
        root.addSubview(sv);
        
        this.setView(root);
    }
    
	ArrayList<String> doXML(String newOrigin) {

		class BARTXMLParser extends NSXMLParserDelegate {
			private String startTag = "";
			private String endTag = "";
			private boolean didFindOrigin = false;
			private String origin;
		    private ArrayList<String> realTimeData = new ArrayList<String>();
		    
		    public BARTXMLParser(String newOrigin) {
		    	origin = newOrigin;
		    }
		    
			@Override
			public void didStartElement(NSXMLParser parser, String elementName, String namespaceURI,
					String qualifiedName, Map<String, String> attributes) {

				startTag = qualifiedName;
			}

			@Override
			public void foundCharacters(NSXMLParser parser, String characters) {
				//System.out.println("//StartTag: " + startTag + " //EndTag: "+ endTag + " //InnerText: "+ characters);

				if (didFindOrigin) {
					//date
					if(startTag.equalsIgnoreCase("date") && endTag.equalsIgnoreCase("abbr")) {
						realTimeData.add(characters);
						//System.out.println("date = " + characters);
					}
					//current time
					if(startTag.equalsIgnoreCase("time") && endTag.equalsIgnoreCase("date")) {
						realTimeData.add(characters);
						//System.out.println("time = " + characters);
						//System.out.println("----------------------");
					}
					//destination
					if(startTag.equalsIgnoreCase("destination") && endTag.equalsIgnoreCase("time")) {
						realTimeData.add(characters);
						//System.out.println("destination = " + characters);
					}
					//destination
					if(startTag.equalsIgnoreCase("destination") && endTag.equalsIgnoreCase("eta")) {
						realTimeData.add(characters);
						//System.out.println("destination = " + characters);
					}
					//arrival times
					if(startTag.equalsIgnoreCase("estimate") && endTag.equalsIgnoreCase("destination")) {
						realTimeData.add(characters);
						//System.out.println("arrival times = " + characters);
					}
					if(startTag.equalsIgnoreCase("name") && endTag.equalsIgnoreCase("station")) {
						didFindOrigin = false;
						//System.out.println();
					}
				}

				//origin
				if(startTag.equalsIgnoreCase("name") && endTag.equalsIgnoreCase("channel")) {
					if (origin.equalsIgnoreCase(characters)) {
						didFindOrigin = true;
						realTimeData = new ArrayList<String>();
						realTimeData.add(characters);
						//System.out.println("origin = " + characters);
					}
				}
				//origin
				if(startTag.equalsIgnoreCase("name") && endTag.equalsIgnoreCase("station")) {	
					if (origin.equalsIgnoreCase(characters)) {
						didFindOrigin = true;
						realTimeData = new ArrayList<String>();
						realTimeData.add(characters);
						//System.out.println("origin = " + characters);
					}
				}
			}

			@Override
			public void didEndElement(NSXMLParser parser, String elementName, String namespaceURI,
					String qualifiedName) {

				endTag = qualifiedName;
			}
			
			public ArrayList<String> getRealTimeData() {
				return realTimeData;
			}
		}

		//XML
		NSURL url = NSURL.URLWithString("http://bart.gov/dev/eta/bart_eta.xml");
		NSMutableURLRequest request = (NSMutableURLRequest)NSMutableURLRequest.requestWithURL(url);
		NSHTTPURLResponseHolder response = new NSHTTPURLResponseHolder();
		NSErrorHolder error = new NSErrorHolder();
		NSData data = NSURLConnection.sendSynchronousRequest(request, response, error);
		//NSLog.log(new String(data.getBytes()));

		NSData xml = NSData.dataWithBytes(data.getBytes());
		NSXMLParser xmlParser = new NSXMLParser(xml);
		BARTXMLParser theParser;
		xmlParser.setDelegate(theParser = new BARTXMLParser(newOrigin));
		xmlParser.parse();
		
		return theParser.getRealTimeData();
	}
}